package.cpath = "luaclib/?.so;3rd/lua-cjson/?.so;"
package.path = "lualib/?.lua;3rd/json/?.lua;server_websocket/?.lua"
local skynet = require "skynet"
local mc = require "multicast" 
local socket = require "socket"
local string = require "string"
local websocket = require "websocket"
local httpd = require "http.httpd"
local urllib = require "http.url"
local sockethelper = require "http.sockethelper" 
local json   = require "cjson"

local packdeal = {} 
 
function packdeal.send_package(id,ack,room_id,uid)
    local data = json.encode(ack)
    if room_id ~= nil then
        packdeal.writelog(room_id,"send:="..uid.."=="..data)
    else
        if  ack.cmd ~= 6 and ack.cmd ~= 62 then
            skynet.error("send:==="..data)
        end  
    end  

    local frame = string.pack("B", 0x80 | 0x1)
    local l = #data 

    local  mask_bit = 0
    if l < 126 then
        frame = frame .. string.pack("B", l | mask_bit)
    elseif l < 0xFFFF then
        frame = frame .. string.pack(">BH", 126 | mask_bit, l)
    else 
        frame = frame .. string.pack(">BL", 127 | mask_bit, l)
    end  
    frame = frame .. data 
    return socket.write(id, frame)   
end  
function packdeal.unpack_package(text,room_id,uid)
    --[[
    local size = #text
    if size < 2 then
        return nil
    end
    local s = text:byte(1) * 256 + text:byte(2) -- s == pack_len -> size == s + 2
    if size < s+2 then
        return nil
    end

    return json.decode(text:sub(3,2+s))
    ]]

	if string.len(text) > 3 then  
        if room_id ~= nil then
            packdeal.writelog(room_id,"receive:="..uid.."=="..text)
        else 
            if text ~= '{"cmd":5,"rs":1}' and text ~= '{"cmd":5,"rs":2}' and text ~= '{"cmd":61}' then
            -- if text ~= '{"cmd":5}' and text ~= '{"cmd":61}' then
                skynet.error("receive:==="..text)
            end  
        end
        return json.decode(text)
    end
end

function packdeal.writelog(file,text)
    if file then   
        local date=os.date("%m-%d");
        -- os.execute("mkdir /skynet/log/"..date)
        local file2= assert(io.open("/skynet/log/"..date..'/'..file,"a"))
        file2:write(text.."\n")
        file2:close()
    end
end
function packdeal.writelog_error(file,text)
    if file then   
        local date=os.date("%m-%d");
        -- os.execute("mkdir /skynet/log/"..date)
        local file2= assert(io.open("/skynet/log/"..date..'/'..file,"a"))
        file2:write(text.."\n")
        file2:close()
    end
end

function packdeal.vdump(obj)
	skynet.error(json.encode(obj))
end

return packdeal
